package com.emokili.ewa.common.exception;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.emokili.ewa.common.enums.HttpStatusEnum;
import com.emokili.ewa.common.utils.MessageResourceUtil;
import com.emokili.ewa.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;

/**
 * @author yuepanpan
 */
@Slf4j
@ControllerAdvice
public class EwaExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R handleException(Exception e) {
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException) e;
            Enum enums = businessException.getEnums();
            if(ObjectUtil.isNull(enums)){
                return R.error(businessException.getMessage());
            }
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String lang = request.getHeader("lang") == null ? "en_US":request.getHeader("lang");
            Class clazz = enums.getClass();
            try{
                String code = (String) clazz.getDeclaredMethod("getCode").invoke(enums);
                String message = MessageResourceUtil.getMessage(code,lang,businessException.getBindArgs());
                log.error("error code:{},error message:{}",code,message);
                //把错误码和错误信息一并返回到调用端
                return R.error(code,message);
            }catch (Exception ex){
                log.error(ex.getMessage(),ex);
                return R.error(ex.getMessage());
            }
        }else {
            log.error("system exception",e);
            return R.error(HttpStatusEnum.SC_INTERNAL_SERVER_ERROR.getCode(),HttpStatusEnum.SC_INTERNAL_SERVER_ERROR.getMessage());
        }
    }
}
